package common.correspondence;

import common.Announcement;
import common.Node;
import common.Utility;

import java.util.HashMap;
import java.util.Vector;

public abstract class BDDTransferAbstract implements BDDTransfer{
    @Override
    public HashMap<Integer, Vector<Integer>> stringToCountTable(String s) {
        HashMap<Integer, Vector<Integer>> table = new HashMap<>();
        String[] kvs = s.split("\\|");

        for(String kv:kvs){
            String[] token = kv.split("/");
            String predicateStr = token[0];
            String[] countStr = token[1].split("\\s+");
            Vector<Integer> count = new Vector<>();
            int predicate = stringToBdd(predicateStr);
            for(String c:countStr)
                count.add(Integer.parseInt(c));
            table.put(predicate, count);
        }
        return table;
    }

    @Override
    public String countTableToString(HashMap<Integer, Vector<Integer>> table) {
        StringBuilder sb = new StringBuilder();
        for(Integer p:table.keySet()){
            sb.append(bddToString(p)).append("/");
            sb.append(Utility.IntegerArrayJoin(" ", table.get(p)));
            sb.append("|");
        }
        return sb.toString();
    }

    @Override
    public String CibInAnnouncementToString(Vector<Announcement> ans) {
        StringBuilder sb = new StringBuilder();
        for(Announcement al: ans){
            sb.append(al.id).append("/");
            sb.append(bddToString(al.predicate)).append("/");
            sb.append(Utility.IntegerArrayJoin(" ", al.count));
            sb.append("|");
        }
        if(ans.size()>0) sb.delete(sb.length()-1, sb.length());
        return sb.toString();
    }

    @Override
    public Vector<Announcement> stringToCibInAnnouncement(String s) {
        Vector<Announcement> res = new Vector<>();
        String[] kvs = s.split("\\|");

        for(String kv:kvs){
            String[] token = kv.split("/");
            if(token.length<3){
                continue;
            }
            String idStr = token[0];
            String predicateStr = token[1];
            String[] countStr = token[2].split("\\s+");
            Vector<Integer> count = new Vector<>();
            int id = Integer.parseInt(idStr);
            int predicate = stringToBdd(predicateStr);
            for(String c:countStr)
                count.add(Integer.parseInt(c));
            Announcement a = new Announcement(id, predicate, count);
            res.add(a);
        }
        return res;
    }
}
